import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'
import './index.scss'
import { Breadcrumb, Button, Card, Form, Input, Select, Upload } from 'antd'
import { Link, useNavigate } from 'react-router-dom'
import { message } from 'antd'
import {  useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { getUserInfoModifyAPI } from '@/api/user'
import { setUserOtherInfo } from '@/store/modules/userOtherInfo'
import { getToken } from '@/utils/token'

const { Option } = Select
const EditInfo = () => {
  // 表单样式
  const formItemLayout = {
    labelCol: {
      xs: {
        span: 24,
      },
      sm: {
        span: 6,
      },
    },
    wrapperCol: {
      xs: {
        span: 24,
      },
      sm: {
        span: 14,
      },
    },
  }

  // 上传头像前的回调函数
  const beforeUpload = (file) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        message.error('Image must smaller than 2MB!')
      }
      return isJpgOrPng && isLt2M
    }

    // 获取用户头像和个人信息进行回显
  const userOtherInfo = useSelector(state => state.userOtherInfo.userOtherInfo)
  const [loading, setLoading] = useState(false)
  const dispatch = useDispatch()
  const handleChange = (info) => {
    if (info.file.status === 'uploading') {
      setLoading(true)
      return
    }
    if (info.file.status === 'done') {
      const imageUrl = info.file.response.data 
      const updatedUser = { ...userOtherInfo, avatar: imageUrl }
      dispatch(setUserOtherInfo(updatedUser)) // 调用 action 更新用户信息
    }
  }

  // 上传头像
  const uploadButton = (
      <button
        style={{
          border: 0,
          background: 'none',
          marginTop: 25
        }}
        type="button"
      >
        {loading ? <LoadingOutlined /> : <PlusOutlined />}
        <div
          style={{
            marginTop: 8,
          }}
        >
          上传照片
        </div>
      </button>
    )

    // 获取用户信息
  const userInfo = useSelector(state => state.user.userInfo)
  // 更新个人信息
  const navigate = useNavigate()
  const onFinish = async formValue => {
    const {gender, phone} = formValue
    const res = await getUserInfoModifyAPI(
      {
        ...userInfo,
        id: userInfo.id,
        phone,
        gender
      })
    if (res.code === 1) {
      message.success('修改成功')
      navigate('/personal')
    } else {
      message.error(res.msg)
    }
  }

  // 个人介绍
  const handleProfileUpdate = (newProfile) => {
    // 更新用户信息的方法
    const updatedUser = { ...userOtherInfo, profile: newProfile }
    dispatch(setUserOtherInfo(updatedUser))
  }
  
  return (
    <div className="edit-info">
      <Card 
        className="edit-container"
        title={
            <Breadcrumb items={[
              { title: <Link to={'/personal'}>个人中心</Link> },
              { title: '编辑资料' },
            ]}
            />
          }>
        <Form
          {...formItemLayout}
          onFinish={onFinish}
          size='large'
          variant="filled"
          style={{
            maxWidth: 700,
          }}
          >
            <Form.Item
                label="用户头像"
                name="image">
                <Upload
                  name="image"
                  listType="picture-circle"
                  className="avatar-uploader"
                  showUploadList={false}
                  action={'http://localhost:8080/upload'}
                  beforeUpload={beforeUpload}
                  onChange={handleChange}
                  headers={{
                    token: getToken()
                    // 其他自定义头信息
                }}
                >
                  {userOtherInfo.avatar ? (
                    <img
                      src={userOtherInfo.avatar}
                      alt="avatar"
                      className="uploaded-image rounded-image"
                    />
                  ) : (
                    uploadButton
                  )}
            </Upload>
            </Form.Item>
            <Form.Item
                label="用户名"
                name="username"
                initialValue={userInfo.username}
                rules={[
                {
                    required: true,
                    message: '请输入用户名',
                },
                ]}
            >
                <Input
                    placeholder="请输入用户名"
                    defaultValue={userInfo.username}
                    size="large"/>
            </Form.Item>
            <Form.Item
                label="用户性别"
                name="gender"
                initialValue={userInfo.gender}
                rules={[
                {
                    required: true,
                    message: '请选择您的性别',
                },
                ]}
            >
                <Select 
                    placeholder="请选择您的性别" 
                    defaultValue={userInfo.gender}
                    size='large'>
                    <Option value="male"  >男</Option>
                    <Option value="female">女</Option>
                </Select>
            </Form.Item>
            <Form.Item
                label="用户手机号码"
                name="phone"
                initialValue={userInfo.phone}
                rules={[
                  {
                    required: true,
                    message: '请输入电话号码',
                  },
                  {
                    pattern: /^1[3-9]\d{9}$/,
                    message: '手机号码格式不对'
                  }
                ]}
              >
                <Input
                  size='large'
                  placeholder="请输入手机号码"
                  defaultValue={userInfo.phone}
                  style={{
                    width: '100%',
                  }}
                />
            </Form.Item>
            <Form.Item
                name="intruduce"
                label="个人简介"
            >
                <Input.TextArea
                size='large'
                placeholder="请输入自我介绍"
                defaultValue={userOtherInfo.profile}
                value={userOtherInfo.profile}
                onChange={(e) => handleProfileUpdate(e.target.value)}
                showCount 
                maxLength={600}
                style={{
                    width: '100%',
                }}
                />
            </Form.Item>
            <Form.Item>
              <Button 
                className='save'
                htmlType="submit"
                size='large'
                >
                保存
              </Button>
            </Form.Item>
        </Form>
      </Card>
    </div>
  )
}


export default EditInfo